﻿using System.Windows;

using log4net;

using VSTalk.Engine.Core.EnvironmentManagers.UI;
using VSTalk.Logger;

namespace VSTalk.Engine.Utils
{
    public class ResourceLoader
    {
        private static readonly ILog _log = LoggerFactory.Create(typeof(ResourceLoader));

        private static IResourceStore ResourceStore
        {
            get { return WindowManager.ResourceStore; }
        }

        private static IWindowManager WindowManager
        {
            get { return AppServices.Get<IWindowManager>(); }
        }

        public static bool GetEnabled(DependencyObject obj)
        {
            return (bool)obj.GetValue(EnabledProperty);
        }

        public static void SetEnabled(DependencyObject obj, bool value)
        {
            obj.SetValue(EnabledProperty, value);
        }

        // Using a DependencyProperty as the backing store for Enabled.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EnabledProperty =
            DependencyProperty.RegisterAttached("Enabled", typeof(bool), typeof(ResourceLoader), new PropertyMetadata(false, EnabledChangedCallback));

        private static void EnabledChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var window = dependencyObject as Window;
            if (window == null)
            {
                _log.Warn("Cannot apply dependency theme for control " + dependencyObject.GetType().FullName);
                return;
            }
            var resources = ResourceStore.GetActualResources();
            foreach (var resourceDictionary in resources)
            {
                window.Resources.MergedDictionaries.Add(resourceDictionary);
            }
        }
    }
}